<!--
  * 码牌表
  *
  * @Author:    zhoujk
  * @Date:      2025-01-26 06:40:43
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="商户名称" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.companyNameLeftLike" placeholder="商户名称" />
      </a-form-item>
      <a-form-item label="状态" class="smart-query-form-item">
        <SmartEnumSelect width="200px" v-model:value="queryForm.activeStatus" enumName="ZZB_DEVICE_ACTIVE_STATUS_ENUM" placeholder="状态" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="showForm" type="primary" size="small" v-privilege="'code:insert'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <!-- <TableOperator v-model="columns" :tableId="null" :refresh="queryData" /> -->
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading" :pagination="false">
      <template #bodyCell="{ text, record, column }">
        <!-- 有图片预览时 注释解开并把下面的'picture'修改成自己的图片字段名即可 -->
        <!-- <template v-if="column.dataIndex === 'picture'">
                  <FilePreview :fileList="text" type="picture" />
                </template> -->

        <!-- 使用字典时 注释解开并把下面的'data-dictionaries'修改成自己的字典字段名即可 有多个字典字段就复制多份同理修改 不然不显示字典 -->
        <!-- 方便修改tag的颜色 orange green purple success processing error default warning -->
        <!-- <template v-if="column.dataIndex === 'data-dictionaries'">
                <a-tag color="cyan">
                  {{ text && text.length > 0 ? text.map((e) => e.valueName).join(',') : '暂无' }}
                </a-tag>
              </template> -->

        <template v-if="column.dataIndex === 'activeStatus'">
          <a-tag :color="statusTypeColorArray[text]">{{ $smartEnumPlugin.getDescByValue('ZZB_DEVICE_ACTIVE_STATUS_ENUM', text) }}</a-tag>
        </template>

        <template v-if="column.dataIndex === 'action'">
          <a-qrcode :ref="(el) => (qrRefs[record.key] = el)" value="{{record.url}}" hidden="hidden" />
          <div class="smart-table-operate">
            <a-button @click="downloadChange(record.key, record)" type="link" v-if="record.activeStatus != 2" v-privilege="'code:download'"
              >下载二维码</a-button
            >
            <a-button @click="updateCancel(record.id)" type="link" v-if="record.activeStatus != 2" v-privilege="'code:update_cancel'">作废</a-button>
            <!--            <a-button-->
            <!--              v-if="-->
            <!--                record.activeStatus === ZZB_DEVICE_ACTIVE_STATUS_ENUM.DEVICE_ACTIVE_STATUS_ACTIVE.value &&-->
            <!--                record.status === ZZB_ENABLE_STATUS_ENUM.ENABLE_STATUS.value-->
            <!--              "-->
            <!--              @click="updateStatus(record.id, false)"-->
            <!--              type="link"-->
            <!--            >-->
            <!--              禁用-->
            <!--            </a-button>-->
            <!--            <a-button-->
            <!--              v-if="-->
            <!--                record.activeStatus === ZZB_DEVICE_ACTIVE_STATUS_ENUM.DEVICE_ACTIVE_STATUS_ACTIVE.value &&-->
            <!--                record.status === ZZB_ENABLE_STATUS_ENUM.DISABLE_STATUS.value-->
            <!--              "-->
            <!--              @click="updateStatus(record.id, true)"-->
            <!--              type="link"-->
            <!--            >-->
            <!--              启用-->
            <!--            </a-button>-->
          </div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <CodesForm ref="formRef" @reloadList="queryData" />
    <UpdateCancelModal ref="cancelActiveStatusRef" @success="queryData" />
  </a-card>
</template>
<script setup>
  import { reactive, ref, onMounted } from 'vue'
  import { codeApi } from '/@/api/business/b-agent/code/code-api'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { smartSentry } from '/@/lib/smart-sentry'
  import TableOperator from '/@/components/support/table-operator/index.vue'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import CodesForm from './code-form.vue'
  import { message } from 'ant-design-vue'
  import UpdateCancelModal from './update-cancel-modal.vue'

  // ---------------------------- 表格列 ----------------------------
  const statusTypeColorArray = ['orange', 'blue', 'red']

  const columns = ref([
    {
      title: '码牌编码',
      dataIndex: 'code',
      ellipsis: true,
    },
    {
      title: '商户名称',
      dataIndex: 'merchantName',
      ellipsis: true,
    },
    {
      title: '激活状态',
      dataIndex: 'activeStatus',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 300,
    },
  ])

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    codeType: 0,
    companyNameLeftLike: undefined, //商户名称
    activeStatus: undefined, //状态
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryData()
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      let queryResult = await codeApi.page(queryForm)
      console.log('数据-===》', queryResult)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  onMounted(queryData)

  // ---------------------------- 添加/修改 ----------------------------
  const formRef = ref()

  function showForm(data) {
    formRef.value.show(data)
  }

  // ---------------------------- 下载二维码 ----------------------------
  const qrRefs = ref([])
  const downloadChange = async (index, record) => {
    const params = {
      code: record.code,
    }
    await codeApi.downloadCode(params).then((res) => {
      // console.log('下载二维码-===》', res)
      if (res.data.code != 200) return message.error(res.data.msg)

      const url = res.data.data.urlBase64Image
      //下载
      const link = document.createElement('a')
      link.href = url
      link.download = res.data.data.code + '.png'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    })
  }

  // ---------------------------- 作废二维码 ----------------------------
  const cancelActiveStatusRef = ref()
  async function updateCancel(record) {
    if (!cancelActiveStatusRef.value) {
      message.error('组件未加载完成，请稍后重试')
      return
    }
    cancelActiveStatusRef.value.show(record)
  }

  // ---------------------------- 更新状态二维码 ----------------------------
  async function updateStatus(id, status) {
    loading.value = true
    try {
      const params = {
        id: id,
        status: status,
      }
      await codeApi.updateStatus(params)
      message.success('操作完成')
      emits('success')
      onClose()
    } catch (error) {
      smartSentry.captureError(error)
      message.error('操作失败')
    } finally {
      loading.value = false
    }
  }
  async function updateStatusDisable(id) {
    await updateStatus(id, false)
  }

  async function updateStatusEnable(id) {
    await updateStatus(id, true)
  }
</script>
